import os
import random

import logging
from flask import current_app
from flask import render_template
from flask import session


from manager import create_app
from utils.qiniu_sdk import put_qiniu

app = create_app()
from manager import redis_store
from manager import db
import models

from flask.ext.migrate import Migrate, MigrateCommand
from flask.ext.script import Manager

# 创建manager对象，管理app
manager = Manager(app)

# 使用Migrate将app和db关联起来
Migrate(app, db)

# 添加操作命令使用，MigrateCommand
manager.add_command('db', MigrateCommand)

#添加用户
def add_user():

    #0,定义用户列表
    user_list = []
    #1,创建管理员对象
    for i in range(1,10):
        user = models.User()
        user.phone="1353022627%s" %i
        user.pwd_hash = "pbkdf2:sha256:50000$tpohFybh$92cff94397c7effe3d845ed7a5aa1145966b4b3413c5bb0eeb921b01c56045f3"
        user.name = "小美%s"%i
        user.id_name = "小小美%s"%i
        user.id_card = "44512119950330485%s"%i

        user_list.append(user)

    #2,保存到数据库中
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"

    return "创建成功"

#添加房子
def add_house():
    user_list = []
    for i in range(1, 20):
        house = models.House()
        house.user_id=random.randint(1,3)
        house.area_id=random.randint(1,2)
        house.title="房子%s" %i
        house.price=random.randint(1000,2000)
        house.address="北京四环院%s号房" %i
        house.room_count=random.randint(2,4)
        house.unit="%s房%s厅" %(random.randint(1,3),random.randint(1,3))
        house.beds="%s人床" %i
        house.max_days=random.randint(55,88)

        user_list.append(house)

        # 2,保存到数据库中
    try:
        db.session.add_all(user_list)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return "创建失败"

    return "创建成功"

#添加房子图片
def add_house_image():
    try:
        housr_list = models.House.query.all()
        i = 0
        for file_name in os.listdir("/home/python/Desktop/image2"):
            with open("/home/python/Desktop/image2/" + file_name, 'rb') as f:
                img_url = put_qiniu(f)
                print(img_url)
                housr_list[i].index_image_url = img_url
                i = i + 1
        db.session.commit()
    except Exception as e:
        logging.error(e)


if __name__ == '__main__':
    manager.run()
    # add_user()
    # add_house()
    # add_house_image()

    